package com.shph.validation.adapter;

import com.shph.validation.Validator;
import com.shph.validation.adapter.impl.ClassRuleParse;
import com.shph.validation.adapter.impl.EnumRuleParse;
import com.shph.validation.adapter.impl.RuleParseImpl;
import com.shph.validation.adapter.impl.StringRuleParse;
import com.shph.validation.rule.IRule;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

public class RuleParseAdapter {
    // 缓存解析器
    private static final Map<Class, RuleParse> cacheRuleParse;

    static {
        cacheRuleParse = new ConcurrentHashMap<>();
    }

    public RuleParse support(Class clazz) {
        if (clazz == Class.class) {
            // ClassRuleParse 对象本身
            RuleParse parse = cacheRuleParse.get(clazz);
            return Optional.ofNullable(parse).orElseGet(() -> {
                RuleParse ruleParse = new ClassRuleParse();
                cacheRuleParse.put(clazz, ruleParse);
                return ruleParse;
            });
        } else if (clazz == String.class) {
            // StringRuleParse 对象本身
            RuleParse parse = cacheRuleParse.get(clazz);
            return Optional.ofNullable(parse).orElseGet(() -> {
                RuleParse ruleParse = new StringRuleParse();
                cacheRuleParse.put(clazz, ruleParse);
                return ruleParse;
            });
        } else if (clazz == Validator.Strategy.class) {
            // StringRuleParse 对象本身
            RuleParse parse = cacheRuleParse.get(clazz);
            return Optional.ofNullable(parse).orElseGet(() -> {
                RuleParse ruleParse = new EnumRuleParse();
                cacheRuleParse.put(clazz, ruleParse);
                return ruleParse;
            });
        } else {
            // RuleParseImpl 对象本身
            RuleParse parse = cacheRuleParse.get(IRule.class);
            return Optional.ofNullable(parse).orElseGet(() -> {
                RuleParse ruleParse = new RuleParseImpl();
                cacheRuleParse.put(IRule.class, ruleParse);
                return ruleParse;
            });
        }
    }
}
